let pomelo = require('pomelo');
let enumeration = require('../../../constant/enumeration');
let code = require('../../../constant/code');
let accountServices = require('../../../services/accountServices');
let commonDao = require('../../../dao/commonDao');
let logger = require('pomelo-logger').getLogger('logic');
let authServices = require('../../../services/authServices');
let token = require('../../../util/token');
let utils = require('../../../util/utils');
let wechartConfig = require('../../../../config/wechart');
let axios = require('axios');
const os = require('os');

let TOKEN_RECONNETION_INVALID_TIME = 24 * 60 * 60 * 1000;

module.exports = function (app, http) {
    // 帐号注册
    http.post('/register', async function (req, res) {

        res.header("Access-Control-Allow-Origin", "*");
        res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
        res.header("Access-Control-Allow-Headers", "X-Requested-With");
        res.header('Access-Control-Allow-Headers', 'Content-Type');

        let account = req.body.account || null;
        let password = req.body.password || null;
        let loginPlatform = req.body.loginPlatform || null;
        loginPlatform = parseInt(loginPlatform);
        let registerInfo = req.body.registerInfo || JSON.stringify({});
        let smsCode = req.body.smsCode || "";
        let saveData = {};
        let matchData = {};
        if (loginPlatform === enumeration.loginPlatform.ACCOUNT) {
            if (!accountServices.checkAccountAndPassword(account, password, loginPlatform)) {
                res.json({ code: code.REQUEST_DATA_ERROR });
                return;
            }
            matchData.account = account;
            saveData.account = account;
            saveData.password = password;
            saveData.registerInfo = JSON.stringify(registerInfo);
        } else if (loginPlatform === enumeration.loginPlatform.WEI_XIN) {
            matchData.wxAccount = account;
            saveData.wxAccount = account;
            saveData.registerInfo = JSON.stringify(registerInfo);
        } else if (loginPlatform === enumeration.loginPlatform.MOBILE_PHONE) {

            let nickname = req.body.nickname;
            if (!nickname) {
                res.json({ code: code.REQUEST_DATA_ERROR });
                return;
            }
            //判断昵称是否存在
            let curData = await commonDao.findOneData('userModel', { nickname: nickname });
            if (curData) {
                res.json({ code: code.NICKNAME_EXIST });
                return;
            }
            //必须要验证码
            if (!smsCode) {
                res.json({ code: code.SMS_CODE_ERROR });
                return;
            } else {
                if (!await authServices.authSmsCode(account, smsCode)) {
                    res.json({ code: code.SMS_CODE_ERROR });
                    return;
                }
            }
            matchData.phoneAccount = account;
            saveData.phoneAccount = account;
            saveData.password = password;
            saveData.registerInfo = JSON.stringify(registerInfo);
        }
        try {

            let accountData = await commonDao.findOneData("accountModel", matchData);
            if (loginPlatform === enumeration.loginPlatform.ACCOUNT || loginPlatform === enumeration.loginPlatform.MOBILE_PHONE) {
                if (!!accountData) {
                    res.json({ code: code.ACCOUNT_EXIST });
                    return;
                }
            }

            if (!accountData) {
                let uid;
                let index = 100;
                // 创建新账户
                while (index > 0) {
                    uid = utils.getRandomNum(100000, 999999);
                    let data = await commonDao.findOneData("accountModel", { uid: uid });
                    let users = await commonDao.findOneData("userModel", { uid: uid });
                    if (!data && !users) break;
                    // 放置操作次数太多锁死
                    index--;
                    if (index <= 0) {
                        res.json({ code: code.FAIL });
                        return;
                    }
                }
                saveData.uid = uid;
                accountData = await commonDao.createData("accountModel", saveData);
            }
            let msg = accountServices.dispatcherServers(pomelo.app.getServersByType('connector'), accountData.uid);
            if (!msg) {
                res.json({ code: code.GET_HALL_SERVERS_FAIL });
            } else {
                res.json({ code: code.OK, msg: msg });
            }
        } catch (err) {
            logger.error("register err:" + JSON.stringify(err));
            res.json({ code: err });
        }
    });

    // 帐号登录
    http.post('/login', async function (req, res) {


        res.header("Access-Control-Allow-Origin", "*");
        res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
        res.header("Access-Control-Allow-Headers", "X-Requested-With");
        res.header('Access-Control-Allow-Headers', 'Content-Type');


        let account = req.body.account || null;
        let password = req.body.password || null;
        let loginPlatform = parseInt(req.body.loginPlatform) || null;
        if (!account || !loginPlatform) {
            res.json({ code: code.REQUEST_DATA_ERROR });
            return;
        }
        let matchData = {};
        if (loginPlatform === enumeration.loginPlatform.ACCOUNT) {
            matchData.account = account;
            matchData.password = password;
        } else if (loginPlatform === enumeration.loginPlatform.WEI_XIN) {
            matchData.wxAccount = account;
        } else {

            let smsCode = req.body.smsCode;
            if (req.body.smsCode && smsCode.length != 0 && smsCode != 'undefined' && smsCode != 'null') {
                if (!await authServices.authSmsCode(account, smsCode)) {
                    res.json({ code: code.SMS_CODE_ERROR });
                    return;
                }
                matchData.phoneAccount = account;
            } else {
                //手机密码登录
                matchData.phoneAccount = account;
                matchData.password = password;
            }
        }
        let result = await commonDao.findOneData("accountModel", matchData);
        if (!result) {
            res.json({ code: code.INVALID_UERS });
        } else {
            let msg = accountServices.dispatcherServers(pomelo.app.getServersByType('connector'), result.uid);
            if (!msg) {
                res.json({ code: code.GET_HALL_SERVERS_FAIL });
            } else {
                res.json({ code: code.OK, msg: msg });
            }
        }
    });

    // 重连
    http.post('/reconnection', async function (req, res) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
        res.header("Access-Control-Allow-Headers", "X-Requested-With");
        res.header('Access-Control-Allow-Headers', 'Content-Type');
        // 检查token
        if (!req.body.token) {
            res.json({ code: code.REQUEST_DATA_ERROR });
            return;
        }
        let authInfo = token.parseToken(req.body.token);
        if (!authInfo || !authInfo.serverID || !authInfo.timekey || !authInfo.uid) {
            res.json({ code: code.REQUEST_DATA_ERROR });
            return;
        }
        let nowTime = Date.now();
        if ((nowTime - authInfo.timekey) > TOKEN_RECONNETION_INVALID_TIME) {
            res.json(null, { code: code.TOKEN_INFO_ERROR });
            return;
        }
        let msg = accountServices.dispatcherServers(pomelo.app.getServersByType('connector'), authInfo.uid);
        if (!msg) {
            res.json({ code: code.GET_HALL_SERVERS_FAIL });
        } else {

            res.json({ code: code.OK, msg: msg });
        }
    });


    // 获取微信用户信息
    http.post('/wxInfo', async function (req, res) {

        res.header("Access-Control-Allow-Origin", "*");
        res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
        res.header("Access-Control-Allow-Headers", "X-Requested-With");
        res.header('Access-Control-Allow-Headers', 'Content-Type');
        // 检查code
        if (!req.body.code) {
            res.json({ code: code.REQUEST_DATA_ERROR });
            return;
        }
        let userCode = req.body.code;
        let { appID, appSecret } = wechartConfig.wechart;
        let accessTokenUrl = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appID}&secret=${appSecret}&code=${userCode}&grant_type=authorization_code`;

        axios.get(accessTokenUrl).then((response) => {

            if (response && response.data && response.data.errcode) {
                logger.error("[wxInfo] get access token fail : " + JSON.stringify(response.data));
                res.json({ code: code.FAIL });
                return;
            } else {
                let openId = response.data.openid;
                let accessToken = response.data.access_token;
                let userInfoUrl = `https://api.weixin.qq.com/sns/userinfo?access_token=${accessToken}&openid=${openId}`;
                axios.get(userInfoUrl).then((response) => {
                    res.json({ code: code.OK, msg: response.data });
                    return;

                }).catch((err) => {
                    logger.error("[wxInfo] get userInfo error : " + JSON.stringify(err));
                    res.json({ code: code.FAIL });
                    return;
                });
            }

        }).catch((err) => {
            logger.error("[wxInfo] get access token error : " + JSON.stringify(err));
            res.json({ code: code.FAIL });
            return;
        });

    });



    //上传用户头像
    http.post('/upavatar', async function (req, res) {

        res.header("Access-Control-Allow-Origin", "*");
        res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
        res.header("Access-Control-Allow-Headers", "X-Requested-With");
        res.header('Access-Control-Allow-Headers', 'Content-Type');
        // 检查code
        if (!req.body.uid || !req.body.data) {
            res.json({ code: code.REQUEST_DATA_ERROR });
            return;
        }

        let result = await commonDao.findOneAndUpdate('userModel', { 'uid': req.body.uid }, { 'avater64': req.body.data });
        let code = result ? code.OK : code.FAIL;
        res.json({ code: code, msg: req.body.data });

    });

    // 忘记密码
    http.post('/resetPassword', async function (req, res) {


        res.header("Access-Control-Allow-Origin", "*");
        res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
        res.header("Access-Control-Allow-Headers", "X-Requested-With");
        res.header('Access-Control-Allow-Headers', 'Content-Type');

        let account = req.body.account || null;
        let password = req.body.password || null;
        let smsCode = req.body.smsCode || null;

        if (!account || !password || !smsCode) {
            res.json({ code: code.REQUEST_DATA_ERROR });
            return;
        }

        if (!await authServices.authSmsCode(account, smsCode)) {
            res.json({ code: code.SMS_CODE_ERROR });
            return;
        }

        await commonDao.updateData("accountModel", { 'phoneAccount': account }, { password: password });
        res.json({ code: code.OK });


    });

};
